package io.renren.modules.bs.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.modules.bs.dao.BsDepartmentDao;
import io.renren.modules.bs.entity.BsDepartmentAdministratorEntity;
import io.renren.modules.bs.entity.BsDepartmentEntity;
import io.renren.modules.bs.entity.BsHospitalEntity;
import io.renren.modules.bs.service.BsDepartmentAdministratorService;
import io.renren.modules.bs.service.BsDepartmentService;
import io.renren.modules.bs.service.BsHospitalService;
import io.renren.modules.bs.vo.BsDepartmentTreeVo;
import io.renren.modules.bs.vo.BsDepartmentVo;
import io.renren.modules.bs.vo.DepartmentOptionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service("bsDepartmentService")
public class BsDepartmentServiceImpl extends ServiceImpl<BsDepartmentDao, BsDepartmentEntity> implements BsDepartmentService {

    @Autowired
    private BsHospitalService hospitalService;

    @Autowired
    private BsDepartmentAdministratorService departmentAdministratorService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Integer total = this.baseMapper.getCount(params);
        Integer limit = Integer.parseInt((String) params.get("limit"));
        Integer page = Integer.parseInt((String) params.get("page"));

        params.put("start",(page -1)*limit);
        params.put("page",page);
        params.put("limit",limit);
        List<BsDepartmentVo> departmentVoList = this.baseMapper.list(params);
        PageUtils pageUtils = new PageUtils(departmentVoList,total,page,limit);
        return pageUtils;
    }

    @Override
    public void prohibitOrEnable(Integer id, Integer isFrozen) {
        BsDepartmentEntity departmentEntity = this.getById(id);
        if(departmentEntity == null){
            throw new RuntimeException("未找到该科室");
        }
        departmentEntity.setIsFrozen(isFrozen);
        boolean update = this.updateById(departmentEntity);
        if(!update){
            throw new RuntimeException("更新失败");
        }
    }

    @Override
    public void saveModel(BsDepartmentEntity bsDepartment) {

        QueryWrapper<BsDepartmentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("department_name",bsDepartment.getDepartmentName());
        wrapper.eq("hospital_id",bsDepartment.getHospitalId());
        BsDepartmentEntity departmentEntity = this.getOne(wrapper);
        if(departmentEntity != null){
            throw new RuntimeException("科室名称重复");
        }
        boolean save = this.save(bsDepartment);
        if(!save){
            throw new RuntimeException("保存失败");
        }
    }

    @Override
    public void updateModel(BsDepartmentEntity bsDepartment) {

        QueryWrapper<BsDepartmentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("department_name",bsDepartment.getDepartmentName());
        wrapper.eq("hospital_id",bsDepartment.getHospitalId());
        wrapper.ne("department_id",bsDepartment.getDepartmentId());
        BsDepartmentEntity departmentEntity = this.getOne(wrapper);
        if(departmentEntity != null){
            throw new RuntimeException("科室名称重复");
        }
        boolean update = this.updateById(bsDepartment);
        if(!update){
            throw new RuntimeException("科室修改失败");
        }
    }

    @Override
    public JSONObject getListAndHospital() {

        JSONObject data = new JSONObject();
        List<BsHospitalEntity> hospitalEntityList = hospitalService.list();
        data.put("hospitalList",hospitalEntityList);
        List<BsDepartmentEntity> departmentEntityList = this.list();
        Map<Long, BsHospitalEntity> hospitalMap = hospitalEntityList.stream().collect(Collectors.toMap(BsHospitalEntity::getHospitalId, Function.identity()));
        Map<Long, List<BsDepartmentEntity>> groupBy = departmentEntityList.stream().collect(Collectors.groupingBy(BsDepartmentEntity::getHospitalId));
        List<DepartmentOptionVo> departmentOptionVos = new ArrayList<>();
        for (Map.Entry<Long,List<BsDepartmentEntity>> entry:groupBy.entrySet()) {

            DepartmentOptionVo departmentOptionVo = new DepartmentOptionVo();
            departmentOptionVo.setOptions(entry.getValue());
            departmentOptionVo.setHospitalName(hospitalMap.get(entry.getKey()).getHospitalName());
            departmentOptionVos.add(departmentOptionVo);
        }
        data.put("departmentList",departmentOptionVos);
        return data;
    }

    @Override
    public Integer getExtractableNumber(Long dataValue) {
        return this.baseMapper.getExtractableNumber(dataValue);
    }

    @Override
    public List<BsDepartmentTreeVo> getTreeData(Long parentId) {
        return this.baseMapper.getTreeData(parentId);
    }

    @Override
    @Transactional
    public void removeRecords(List<Long> asList) {
        //检查 管理员
        List<BsDepartmentAdministratorEntity> departmentEntityList =  this.departmentAdministratorService.listByDeptIds(asList);
        if(departmentEntityList.size() > 0){
            throw new RRException("请先删除科室下的管理员");
        }
        //检查住院病人
        this.removeByIds(asList);
    }

    @Override
    public List<BsDepartmentEntity> getListByHospitalIds(List<Long> asList) {

        QueryWrapper<BsDepartmentEntity> bsDepartmentEntityQueryWrapper = new QueryWrapper<>();
        bsDepartmentEntityQueryWrapper.in("hospital_id",asList);
        return list(bsDepartmentEntityQueryWrapper);
    }

}